package net.example.utils;

import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

import java.io.InputStream;

public class AnimatedGifDrawable extends AnimationDrawable {

	private int mCurrentIndex = 0;
	private UpdateListener mListener;

	public AnimatedGifDrawable(InputStream source, UpdateListener listener) {
		mListener = listener;
		GifDecoder decoder = new GifDecoder();
		decoder.read(source);
		for (int i = 0; i < decoder.getFrameCount(); i++) {
			Bitmap bitmap = decoder.getFrame(i);
			BitmapDrawable drawable = new BitmapDrawable(bitmap);
			drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
			addFrame(drawable, decoder.getDelay(i));
			if (i == 0) {
				setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
			}
		}
	}


	public void nextFrame() {
		mCurrentIndex = (mCurrentIndex + 1) % getNumberOfFrames();
		if (mListener != null)
			mListener.update();
	}

	public int getFrameDuration() {
		return getDuration(mCurrentIndex);
	}
	public Drawable getDrawable() {
		return getFrame(mCurrentIndex);
	}
	public interface UpdateListener {
		void update();
	}

}